package graphing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class GraphWindow extends JFrame {
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JPanel graphPane;
	private BufferedImage image;
	public GraphData[] data;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GraphWindow frame = new GraphWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public GraphWindow() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 600, 450);
		setMinimumSize(new Dimension(100,100));
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		graphPane = new JPanel();
		graphPane.setBorder(null);
		contentPane.add(graphPane, BorderLayout.CENTER);
		
		/*
		data = new GraphData();
		data.type = GraphData.SEQUENTIAL;
		data.displayMethod = GraphData.CONNECTED;
		data.autoscale = true;
		float[] y = {1,2,3,4,6,-3,2};
		data.yData = y;
		*/
		draw(false);
		
		graphPane.addComponentListener(new ComponentListener(){
			public void componentHidden(ComponentEvent e){}
			public void componentMoved(ComponentEvent e){
				draw(false);
			}
			public void componentResized(ComponentEvent e){
				draw(true);
			}
			public void componentShown(ComponentEvent e){
				draw(true);
			}
		});
		addComponentListener(new ComponentListener(){
			public void componentHidden(ComponentEvent e){}
			public void componentMoved(ComponentEvent e){
				draw(false);
			}
			public void componentResized(ComponentEvent e){
				draw(true);
			}
			public void componentShown(ComponentEvent e){
				draw(true);
			}
		});
	}

	private void draw(boolean resize){
		if(image == null || resize){
			image = (BufferedImage)createImage(graphPane.getWidth(),graphPane.getHeight());
		}
		if(image != null){
			Graphics2D g = (Graphics2D)image.getGraphics();
			g.setColor(Color.white);
			g.fillRect(0, 0, graphPane.getWidth(), graphPane.getHeight());
			if(data != null){
				for(GraphData d: data){
					d.drawGraph(g, graphPane.getWidth(), graphPane.getHeight());
				}
			}
			g.dispose();
			if(graphPane != null){
				Graphics2D n = (Graphics2D)graphPane.getGraphics();
				if(n != null){
					n.drawImage(image, 0, 0, null);
					n.dispose();
				}
			}
		}
	}
}
